import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
// import { VideoModal } from '@modals/alarm-video/alarm-video';
// import { PromptAlarmModal } from './prompt-alarm/prompt-alarm';
import { Subscription } from 'rxjs';
import { MessageService } from '@services/message.service';

import { DataService } from '@services/data.service';

// import { AlarmDetailPage } from './alarm-detail/alarm-detail';
import { CacheService } from '@services/cache.service';
import { MyNoteService } from '@services/myNote.service';
import { providerDef } from '@angular/core/src/view';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  styleUrls: ['home.scss']
})
export class HomePage implements OnInit {
  userId;
  functionList;
  state = 'alarm';
  alarmDatas = [];  // 告警数据
  fireAlarms = [];  // 消防告警数据
  eventDatas = [];  // 事件数据
  pageIndex = 1;    // 默认页码
  pageSize = 50;
  alarmLevel = 1;
  totalSize = undefined;
  _refreshInterval;
  dealAlarmPermission = true;
  projectId;
  subscription: Subscription;
  constructor(
    private modalCtrl: ModalController,
    private dataService: DataService,
    private cache: CacheService,
    private myNote: MyNoteService,
    private messageService: MessageService
  ) {
    this.userId = this.cache.userinfo.userId;
    this.subscription = this.messageService.getMessage().subscribe(data => {
      if (data.id === 'projectChange' && data.data) {
        this.getFireParams(data.data.projectId, false, true);
      }
    });
  }

  changeAlarmTab(data) {
    this.state = data;
    if (data === 'alarm') {
      this.getAlarm(this.projectId, null);
    } else if (data === 'fireAlarm') {
      this.getFireParams(this.projectId, null, false);
    } else {
      this.getEvent(this.projectId, null, null);
    }
  }

  ngOnInit() {
    this.state = 'alarm';
    this.functionList = [{ functionCode: 'alarm', functionName: '告警' }, { functionCode: 'event', functionName: '事件' }];
  }

  ionViewWillEnter() {
    this.state = 'alarm';
    this.projectId = this.cache.currentProject.projectId;
    this.getAlarm(this.projectId, null);
    this.getFireParams(this.projectId, null, true);
  }

  getAlarm(projecId, refresher) {
    this.dataService.projectAlarmList(projecId).subscribe((val) => {
      console.log(val);
      this.alarmDatas = val.data || [];
      if (refresher) {
        refresher.complete();
      }
    });
  }


  // 获取消防告警列表
  getFireParams(projectId, refresher, isChange) {
    this.dataService.getFireAlarms(projectId).subscribe(res => {
      this.dataService.getHistoryFireAlarms(projectId).subscribe(data => {
        const realTimeAlarm = res.data && res.data.realTimeInfos ? res.data.realTimeInfos : [];
        const historyTimeAlarm = data.data && data.data.historyInfos ? data.data.historyInfos : [];
        this.fireAlarms = realTimeAlarm.concat(historyTimeAlarm);
        if (isChange) {
          if (this.fireAlarms.length) {
            if (this.functionList[1].functionCode === 'fireAlarm') {
              return;
            } else {
              this.functionList.splice(1, 0, { functionCode: 'fireAlarm', functionName: '消防告警' });
            }
          } else {
            if (this.functionList[1].functionCode === 'fireAlarm') {
              this.functionList.splice(1, 1);
            } else {
              return;
            }
          }
        }
      });
      if (refresher) {
        refresher.complete();
      }
    });
  }

  // 获取事件
  getEvent(projecId, infiniteScroll, refresher) {
    // 默认加载第一页数据
    if (typeof this.pageIndex !== 'number') {
      this.pageIndex = 1;
    }

    this.dataService.projectEventList(projecId, this.pageIndex, this.pageSize).subscribe(val => {
      if (this.pageIndex === 1) {
        this.eventDatas = val.data.datas;
      } else {
        Array.prototype.push.apply(this.eventDatas, val.data.datas);
      }
      this.totalSize = val.data.total;
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    });
  }

  eventClick() {
    this.eventDatas = [];
    this.pageIndex = 0;
    this.totalSize = undefined; // 清除总页数记录，否则是否有数据判断可能直接为false
  }

  // 事件分页加载
  loadData(type, infiniteScroll, refresher) {
    if (type === 'refresh') {
      this.pageIndex = 0;
    }
    this.pageIndex++;
    this.getEvent(this.projectId, infiniteScroll, refresher);
  }

  // 下拉刷新
  doRefresh(refresher) {
    if (this.state === 'alarm') {
      this.getAlarm(this.projectId, refresher);
    } else if (this.state === 'fireAlarm') {
      this.getFireParams(this.projectId, refresher, true);
    } else if (this.state === 'event') {
      this.eventClick();
      this.loadData('refresh', null, refresher);
    }
    setTimeout(() => {
      console.log('Async operation has ended');
      if (refresher) {
        refresher.complete();
      }
    }, 15000);
  }

  // 判断是否有更多的数据可以加载
  moreDataCanBeLoaded() {
    // 数据总数请求没有返回时，默认加载
    if (this.totalSize == null) {
      return true;
    }
    let bool = true;
    const pageTotal = Math.ceil(this.totalSize / this.pageSize);
    if (this.pageIndex >= pageTotal) {
      bool = false;
    }
    return bool;
  }


  // showPopup(data) {
  //   console.log(data);
  //   if (data.procState === 0 && !data.isRestore && data.lastCancelUserId !== this.userId) {
  //     const modal = this.modalCtrl.create(PromptAlarmModal, { title: '告警处理' });
  //     modal.present();
  //     modal.onDidDismiss(choose => {
  //       if (choose === 1) {                             // 立即处理
  //         let reqBody;
  //         reqBody = {
  //           ProcState: 1,
  //           DeviceId: data.deviceId,
  //           DeviceParameterId: data.deviceParameterId,
  //           AlarmTypeId: data.alarmTypeId
  //         };
  //         if (data.isRestore === true) {
  //           reqBody.AlarmId = data.alarmId;
  //         }
  //         this.receiveTask(reqBody, data);
  //       } else if (choose === 0) {                      // 查看详情
  //         this.navCtrl.push(AlarmDetailPage, {
  //           alarmInfo: data
  //         });
  //       }
  //     });
  //   } else {
  //     this.navCtrl.push(AlarmDetailPage, {
  //       alarmInfo: data
  //     });
  //   }
  // }

  // receiveTask(reqBody, data) {
  //   this.dataService.dealTask(reqBody).subscribe(res => {
  //     if (res.success) {
  //       data.taskId = res.data;
  //       data.isMy = true;
  //       data.procState = 1;
  //       // let toast;
  //       // toast = this.toastCtrl.create({
  //       //   message: '已成功加入任务列表',
  //       //   duration: 1500,
  //       //   position: 'middle'
  //       // });
  //       // toast.onDidDismiss(() => {
  //       //   this.navCtrl.push(AlarmDetailPage, {
  //       //     alarmInfo: data
  //       //   });
  //       // });
  //       // toast.present();
  //       this.myNote.MyNotice('已成功加入任务列表');
  //       this.navCtrl.push(AlarmDetailPage, {
  //         alarmInfo: data
  //       });

  //     }
  //   });
  // }

  // watchVideo(data) {
  //   const config = {
  //     title: data.RoomName + ' ' + data.DeviceName,
  //     message: data.AlarmTypeName + data.AlarmText,
  //     preload: true,
  //     plugins: {
  //       poster: 'http://120.76.244.22:3000/android/1.5.9/poster.jpg'
  //     },
  //     sources: [{ src: data.VideoUrl, type: 'video/mp4', condition: Math.random() }]
  //   };

  //   const videoModal = this.modalCtrl.create(VideoModal, { config: config });
  //   videoModal.present();
  // }

  eww() {
    alert();
  }
}
